#define _CRT_SECURE_NO_WARNINGS
#include "snake.h"		//引入自定义头文件


int main(void)
{
	CONSOLE_CURSOR_INFO cci;
	cci.dwSize = sizeof(cci);
	cci.bVisible = FALSE;
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci);
	srand(time(NULL));//播种随机数种子。
	
	int mode = '1';
	
	while (mode == '1')
	{
		score = 0;
		speed = SPEED;
		initStart();		//初始化开始界面		
			mode = _getch();
			//mode2退出游戏
			if (mode == '2') {
			printf("已退出");
			return 0;
		}
			//mode3进入游戏规则介绍界面
			if (mode == '3') {
				initRule();
				while (!_kbhit());
				_getch();
				initStart();
				mode = '1';
				continue;
			}
		initSnake();		//初始化蛇
		initFood();			//初始化食物
		initWall();			//画墙
		initUI();			//画蛇和食物

		playGame();			//启动
		//打印分数
		// 在游戏结束处添加以下代码
		system("cls");
		COORD coord = { 0 };
		coord.X = WIDE / 2 - 15;
		coord.Y = HIGH / 2 - 3;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		printf("╔══════════════════════════════╗");
		coord.Y++;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		printf("║        游戏结束!             ║");
		coord.Y++;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		printf("╠══════════════════════════════╣");
		coord.Y++;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		printf("║ 最终得分: %-17d  ║", score);
		coord.Y++;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		int max = Score(score);
		if (score < max) {
			printf("║ 最高纪录: %-17d  ║", max);
		}
		else {
			printf("║ 恭喜! 创造了新纪录!       ║");
		}
		coord.Y++;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		printf("╚══════════════════════════════╝");
		coord.Y += 2;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		printf("按任意键回到开始界面");
		while (!_kbhit()); 
		_getch();
		mode = '1';
	}

	system("pause");
	return EXIT_SUCCESS;
}

//初始化墙
void initWall(void) {
	COORD coord = { 0 };
	coord.X = 0;
	coord.Y = 0;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);

	// 绘制游戏区域边框
	for (int i = 0; i <= HIGH; i++) {
		for (int j = 0; j <= WIDE; j++) {
			if (i == 0 && j == 0) printf("╔");
			else if (i == 0 && j == WIDE) printf("╗");
			else if (i == HIGH && j == 0) printf("╚");
			else if (i == HIGH && j == WIDE) printf("╝");
			else if (i == 0 || i == HIGH) printf("═");
			else if (j == 0 || j == WIDE) printf("║");
			else printf(" ");
		}
		printf("\n");
	}

	// 绘制右侧信息栏边框
	coord.X = WIDE + 1;
	coord.Y = 0;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("╔══════════════╗");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ 游戏信息     ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("╠══════════════╣");

	// 将光标移到底部
	coord.X = 0;
	coord.Y = HIGH + 1;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//初始化游戏
void playGame(void)
{
	char key = 'd';
	//判断蛇撞墙
	while (snake.body[0].X > 0 && snake.body[0].X < WIDE
		&& snake.body[0].Y > 0 && snake.body[0].Y < HIGH)
	{
		//更新蛇
		initUI();

		//接收用户按键输入wasd
		if (_kbhit())		//为真时，用户按下按键
		{
			char _key = _getch();
			if (_key == ' ')//如果是空格就加速
			{
				speed = SPEED/2;
				add = ADD * 2;//得分加倍
			}
			else {
				key = _key;
			}
		}
		else {
			speed = SPEED;
			add = ADD;		//速度和加分回到默认值
		}
		
		switch (key)
		{
		case'w':kx = 0; ky = -1; break;
		case'a':kx = -1; ky = 0; break;
		case's':kx = 0; ky = 1; break;
		case'd':kx = 1; ky = 0; break;
		default:
			break;
		}


		//蛇撞身体
		for (size_t i = 1; i < snake.size; i++)

		{
			if (snake.body[0].X == snake.body[i].X
				&& snake.body[0].Y == snake.body[i].Y)
			{
				return;//游戏结束
			}
		}
		//蛇头撞食物
		if (snake.body[0].X == food.X && snake.body[0].Y == food.Y)
		{
			initFood();		//食物消失

			snake.size++;	//身体增加
			score+=add;		//加分;
		}
		lastX = snake.body[snake.size - 1].X;
		lastY = snake.body[snake.size - 1].Y;
		for (size_t i = snake.size - 1; i > 0; i--)//蛇移动，前一节身体赋值给后一节
		{

			snake.body[i].X = snake.body[i - 1].X;
			snake.body[i].Y = snake.body[i - 1].Y;
		}
		snake.body[0].X += kx;		//蛇头根据用户按键进行修改
		snake.body[0].Y += ky;


		Sleep(speed);
		//清屏
		//system("cls");
	}
	return;
}
//初始化开始界面
void initStart(void)
{
	system("cls");
	COORD coord = { 0 };

	// 绘制精美边框
	coord.X = 0;
	coord.Y = 0;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	for (int i = 0; i <= HIGH; i++) {
		for (int j = 0; j <= WIDE; j++) {
			if (j == WIDE) {
				printf("║");
			}
			else if (i == HIGH) {
				printf("═");
			}
			else if (i == 0 && j == 0) {
				printf("╔");
			}
			else if (i == 0 && j == WIDE) {
				printf("╗");
			}
			else if (i == HIGH && j == 0) {
				printf("╚");
			}
			else if (i == HIGH && j == WIDE) {
				printf("╝");
			}
			else if (i == 0) {
				printf("═");
			}
			else if (j == 0) {
				printf("║");
			}
			else {
				printf(" ");
			}
		}
		printf("\n");
	}

	// 游戏标题艺术字
	// 替换原来的ASCII艺术字标题部分
	// 替换原来的ASCII艺术字标题部分
	coord.X = WIDE / 2 - 12;
	coord.Y = HIGH / 2 - 6;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("%s\n", "███████╗███╗   ██╗ █████╗ ██╗  ██╗███████╗");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("%s\n", "██╔════╝████╗  ██║██╔══██╗██║ ██╔╝██╔════╝");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("%s\n", "███████╗██╔██╗ ██║███████║█████╔╝ █████╗  ");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("%s\n", "╚════██║██║╚██╗██║██╔══██║██╔═██╗ ██╔══╝  ");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("%s\n", "███████║██║ ╚████║██║  ██║██║  ██╗███████╗");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("%s\n", "╚══════╝╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝");

	// 菜单选项框
	coord.X = WIDE / 2 - 10;
	coord.Y = HIGH / 2 + 1;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("┏━━━━━━━━━━━━━━━━━━┓");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("┃  1. 开始游戏     ┃");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("┃  2. 退出游戏     ┃");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("┃  3. 游戏规则     ┃");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("┗━━━━━━━━━━━━━━━━━━┛");

	// 底部提示信息
	coord.X = WIDE / 2 - 20;
	coord.Y = HIGH - 2;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("══════════════════════════════════════════════════");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("使用数字键选择选项，按对应数字继续");

	// 将光标移到底部
	coord.X = 0;
	coord.Y = HIGH + 1;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//游戏规则
void initRule(void)
{
	system("cls");
	COORD coord = { 0 };

	// 绘制精美边框
	coord.X = 0;
	coord.Y = 0;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	for (int i = 0; i <= HIGH; i++) {
		for (int j = 0; j <= WIDE; j++) {
			if (j == WIDE) {
				printf("║");
			}
			else if (i == HIGH) {
				printf("═");
			}
			else if (i == 0 && j == 0) {
				printf("╔");
			}
			else if (i == 0 && j == WIDE) {
				printf("╗");
			}
			else if (i == HIGH && j == 0) {
				printf("╚");
			}
			else if (i == HIGH && j == WIDE) {
				printf("╝");
			}
			else if (i == 0) {
				printf("═");
			}
			else if (j == 0) {
				printf("║");
			}
			else {
				printf(" ");
			}
		}
		printf("\n");
	}

	// 游戏规则标题
	coord.X = WIDE / 2 - 10;
	coord.Y = 2;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("╔══════════════════╗");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║    游戏规则说明  ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("╚══════════════════╝");

	// 规则内容 - 调整为适合控制台宽度的文本
	coord.X = 4;  // 左边距调整为4
	coord.Y = 6;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("◆ 使用WASD键控制蛇的移动方向:");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("   W - 向上移动  A - 向左移动");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("   S - 向下移动  D - 向右移动");
	coord.Y += 2;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("◆ 长按空格键可加速移动，同时得分翻倍");
	coord.Y += 2;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("◆ 吃到食物(#)可以增加蛇的长度和得分");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("◆ 撞到墙壁或自己的身体游戏结束");

	// 分隔线
	coord.X = 4;
	coord.Y = HIGH - 6;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("────────────────────────────────");

	// 蛇和食物示例
	coord.X = WIDE / 2 - 5;
	coord.Y = HIGH - 4;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("示例: ***@ #");

	// 返回提示
	coord.X = WIDE / 2 - 10;
	coord.Y = HIGH - 2;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("按任意键返回主菜单");

	// 将光标移到底部
	coord.X = 0;
	coord.Y = HIGH + 1;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//定义初始化蛇函数
void initSnake(void)
{
	snake.size = 2;
	snake.body[0].X = WIDE / 2;		//初始化蛇头
	snake.body[0].Y = HIGH / 2;
	snake.body[1].X = WIDE / 2 - 1;	//初始化一节蛇身
	snake.body[1].Y = HIGH / 2;

	return;
}

//初始化界面控件
void initUI(void)
{
	COORD coord = { 0 };

	// 画蛇
	for (size_t i = 0; i < snake.size; i++)
	{
		coord.X = snake.body[i].X;
		coord.Y = snake.body[i].Y;
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
		if (i == 0)
		{
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);
			putchar('@'); // 蛇头
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
		}
		else {
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
			putchar('*'); // 蛇身
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
		}
	}

	// 去除蛇尾
	coord.X = lastX;
	coord.Y = lastY;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	putchar(' ');

	// 画食物
	coord.X = food.X;
	coord.Y = food.Y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_INTENSITY);
	putchar('#'); // 食物
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

	// 更新右侧信息栏
	coord.X = WIDE + 1;
	coord.Y = 3;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ 得分: %-6d ║", score);
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║              ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ 操作说明:    ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ W - 上       ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ A - 左       ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ S - 下       ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ D - 右       ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("║ 空格 - 加速  ║");
	coord.Y++;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
	printf("╚══════════════╝");

	// 将光标移到底部
	coord.X = 0;
	coord.Y = HIGH + 1;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//食物的初始化函数
void initFood(void)
{
	food.X = rand() % (WIDE-1)+1;//1-59
	food.Y = rand() % (HIGH-1)+1;//1-59
	//for(int i = 0;i<snake)
}

//记录最高分到score.txt
int Score(int sc) {
	FILE* p = fopen("score.txt", "r+");  // 读写，不截断文件
	if (!p) {
		p = fopen("score.txt", "w+");    // 如果文件不存在，创建新文件
	}

	char max[256] = { 0 };
	int maxscore = 0;

	// 读取当前最高分
	if (fgets(max, sizeof(max), p)) {
		for (int i = 0; max[i] != '\0' && max[i] != '\n'; i++) {
			if (max[i] >= '0' && max[i] <= '9') {  // 确保是数字字符
				maxscore *= 10;
				maxscore += max[i] - '0';
			}
		}
	}

	// 如果新分数更高，写入文件
	if (maxscore < sc) {
		rewind(p);  // 将文件指针移回开头，覆盖原内容
		fprintf(p, "%d", sc);  // 直接写入整数
		maxscore = sc;
	}

	fclose(p);
	return maxscore;
}